package com.gzbsoft.sc.modules.app.service.impl;
import cn.hutool.crypto.digest.DigestUtil;
import com.gzbsoft.sc.common.exception.RRException;
import com.gzbsoft.sc.modules.app.form.LoginForm;
import com.gzbsoft.sc.modules.app.form.RegisterForm;
import com.gzbsoft.sc.modules.app.service.JxUserService;
import com.gzbsoft.sc.modules.sys.dao.JxUserDao;
import com.gzbsoft.sc.modules.sys.entity.JxUser;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

import java.util.Locale;
import java.util.Optional;
@Service
public class JxUserServiceImpl implements JxUserService {
    private final JxUserDao jxUserDao;
    private final MessageSource messageSource;
    public JxUserServiceImpl(JxUserDao jxUserDao, MessageSource messageSource) {
        this.jxUserDao = jxUserDao;
        this.messageSource = messageSource;
    }
    @Override
    public Long login(LoginForm form) {
        JxUser user = jxUserDao.findByProperty("tel", form.getMobile()).orElse(null);
        if (user == null) {
            throw new RRException("手机号或密码错误");
        }
        if (!user.getPassword().equals(DigestUtil.sha256Hex(form.getPassword()))) {
            throw new RRException(messageSource.getMessage("password-invalid", null, Locale.getDefault()));
        }
        return user.getId();
    }
    @Override
    public void register(RegisterForm form) {
        JxUser user = new JxUser();
        user.setTel(form.getMobile());
        user.setUsername(form.getMobile());
        user.setPassword(DigestUtil.sha256Hex(form.getPassword()));
        jxUserDao.save(user);
    }
    @Override
    public Optional<JxUser> getById(Long id) {
        return jxUserDao.findById(id);
    }
}
